package com.demo.Statement应用场景;

import java.sql.*;
import java.util.Scanner;



public class 需要进行sql注入拼接的时候 {
    public static void main(String[] args) {
        //用户在控制台输入desc或者asc
        Scanner s=new Scanner(System.in);
        System.out.println("请输入asc或者desc; asc表示升序，desc表示降序！");
        System.out.print("请输入：");
        String keyWord=s.nextLine();

        //定义全局变量
        Connection con=null;
        Statement sta=null;
        ResultSet rs=null;
        try{
        //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        //获取数据库链接asc
            con= DriverManager.getConnection("jdbc:mysql://localhost:3306/hrs","root","552200");
            System.out.println("数据库连接："+con);
        //获取数据库操作对象
            sta=con.createStatement();
        //执行sql语句
            String sql="select salary from employees order by salary "+keyWord;
            rs=sta.executeQuery(sql);
        //处理查询结果集
            while (rs.next()){
                System.out.println(rs.getString("salary"));
            }

        }catch(Exception e){
            System.out.println("代码出错！");
        }finally {
        //释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (sta != null) {
                try {
                    sta.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
